# -*- coding: utf-8 -*-
# @File     : api.py
# @Author   : bingjia
# @Time     : 2020/8/4 13:08
# @Desc     : 认证模块，提供用户注册和登陆api

from django.db import IntegrityError
from django.contrib.auth import get_user_model
from django.utils.translation import ugettext as _

from ..base.api import viewsets
from ..base.api import response
from ..base.api import exceptions as exc
from ..base.api.utils.decorators import list_route
from ..users.serializers import UserSerializer
from ..base.utils.parse_data import parse_data

from . import signals
from . import services
from . import throttling
from . import permissions
from . import validators


class AuthViewSet(viewsets.ModelViewSet):
    """
    认证视图集
    """
    "权限"
    permission_classes = (permissions.AuthPermission,)
    "序列化"
    serializer_class = UserSerializer
    "节流"
    throttle_classes = (throttling.LoginFailRateThrottle, throttling.RegisterSuccessRateThrottle)

    @list_route(methods=["POST"])
    def login(self, request, **kwargs):
        """
        用户登录
        :param request:
        :param kwargs:
        :return:
        """
        self.check_permissions(request, 'login', None)
        username = request.data.get('username', None)
        password = request.data.get('password', None)

        user = services.get_and_validate_user(username=username, password=password)
        data = services.make_auth_response_data(user)

        return response.Ok(data)

    @list_route(methods=["POST"], detail=False)
    def register(self, request, **kwargs):
        """
        新用户注册
        :param request:
        :param kwargs:
        :return:
        """
        accepted_terms = request.data.get("accepted_terms", None)
        if accepted_terms in (None, False):
            raise exc.BadRequest(_("You must accept our terms of service and privacy policy"))

        self.check_permissions(request, 'register', None)

        try:
            data = parse_data(request.data, cls=validators.RegisterValidator)
            user = services.user_register(**data)
        except exc.ParseError as e:
            raise exc.BadRequest(e.detail)
        serializer = self.get_serializer(user)

        return response.Created(serializer.data)
